package com.chl.legou.order.controller;

import com.chl.legou.order.config.TokenDecode;
import com.chl.legou.order.po.OrderItem;
import com.chl.legou.order.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author chlong
 * @date 2022/2/14
 */
@RestController
@RequestMapping("/cart")
@CrossOrigin //跨域访问
public class CartController {

    @Autowired
    private CartService cartService;

    @Autowired
    private TokenDecode tokenDecode;

    /**
     * 添加到购物车
     *
     * @param id
     * @param num
     * @return
     */
    @RequestMapping("/add")
    public ResponseEntity add(Long id, Integer num) throws IOException {
        //springsecurity 获取当前的⽤户名 传递service
//        String username = "chl";
        Map<String, String> userInfo = tokenDecode.getUserInfo();
        String username = userInfo.get("user_name");
        System.err.println("⽤户名:" + username);
        cartService.add(id, num, username);
        return ResponseEntity.ok("添加成功");
    }

    /**
     * 购物车列表
     * @return
     * @throws IOException
     */
    @RequestMapping("/list")
    public ResponseEntity<List<OrderItem>> list() throws IOException {
//        String username = "chl";
        Map<String, String> userInfo = tokenDecode.getUserInfo();
        String username = userInfo.get("user_name");
        System.err.println("哇塞::⽤户名:" + username);
        List<OrderItem> orderItemList = cartService.list(username);
        return new ResponseEntity<>(orderItemList, HttpStatus.OK);
    }
}
